package com.gateway.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//全局过滤器代码逻辑实现
@Component
//@Order(1):注解配置过滤器的执行顺序
public class GlobalFilter implements GatewayFilter, Ordered {
    /**
     * 处理当前请求，有必要的话通过 {@link GatewayFilterChain} 将请求交给下一个过滤器处理
     *
     * @param exchange 请求上下文，里面可以获取 Request、Response 等信息
     * @param chain 用来把请求委托给下一个过滤器
     * @return {@code Mono<Void>} 返回值标示当前过滤器业务结束
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        String token = params.getFirst("token");
        if("token".equals(token)){
            //放行到下一个过滤器
            return chain.filter(exchange);
        }
        //401：登陆失败
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    //代码配置过滤器顺序
    @Override
    public int getOrder() {
        return 1;
    }

}

